package com.esteel.settlement.pa.service.impl;

import java.util.Date;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.esteel.settlement.entity.TbSettFund;
import com.esteel.settlement.entity.TbSettFundChg;
import com.esteel.settlement.entity.TbSettOutmoney;
import com.esteel.settlement.pa.packet.OutMoneyBP1312;
import com.esteel.settlement.pa.packet.PaPacket;
import com.esteel.settlement.pa.packet.RspBP1303;
import com.esteel.settlement.pa.service.PacketProcesser;
import com.esteel.settlement.service.SettFundChgService;
import com.esteel.settlement.service.SettFundService;
import com.esteel.settlement.service.SettOutmoneyService;

/**
 * 入金操作指令 兼测试类
 * @author zhangxiuzhi
 *
 */
@Service
public class OutMoneyProcesser extends PacketProcesser<OutMoneyBP1312, RspBP1303>  {

	@Autowired
	private SettFundService settFundService;
	
	@Autowired
	private SettFundChgService settFundChgService;
	
	@Autowired
	private SettOutmoneyService settOutmoneyService;
	
	@Transactional
	public RspBP1303 execute(OutMoneyBP1312 packet) {

		//保存数据至出金表
		TbSettOutmoney tbSettOutmoney = new TbSettOutmoney();
		
		double tranAmount = packet.getTranAmount();
		
		BeanUtils.copyProperties(packet, tbSettOutmoney);
		tbSettOutmoney = settOutmoneyService.save(tbSettOutmoney);
		//改变资金账户表数据
		TbSettFund fund  = settFundService.findByCustAcctId(packet.getCustAcctId());
		Assert.notNull(fund,"没有该账户");
		fund.setTotalAmount(fund.getTotalAmount() - tranAmount);
		fund.setTotalBalance(fund.getTotalBalance() - tranAmount);
		settFundService.save(fund);
			
		//增加资金变动流水
		TbSettFundChg settFundChg = new TbSettFundChg();
		BeanUtils.copyProperties(fund.getId(), settFundChg);
		BeanUtils.copyProperties(fund, settFundChg);
		//资金变化类型
		settFundChg.setLinkType(TbSettFundChg.LinkType.OUT);
		settFundChg.setLinkKey(tbSettOutmoney.getOutId());
		settFundChg.setTransDate(fund.getTranDate());
		settFundChg.setChgTotalAmount(tranAmount);
		settFundChg.setChgTotalBalance(tranAmount);
		settFundChgService.save(settFundChg);
		
		
		RspBP1303 rsp = new RspBP1303();

		rsp.setTranFunc("1310");
		rsp.setServType(PaPacket.RESPONSE);
		rsp.setTransDate(new Date());
		rsp.setThirdLogNo("1310_"+tbSettOutmoney.getOutId());
		rsp.setQydm(packet.getQydm());
		rsp.setRspCode(PaPacket.SUCCESS);
		
		return rsp;
	}

	@Override
	protected String getTranFunc() {
		return "1312";
	}





}
